package Test.day16;

public class ProductAndCustomerDemo {
    public static void main(String[] args) {
        Box  box=new Box();
        Thread p=new Product(box);
        p.setName("生产者-》");
        Thread c=new Custermer(box);
        c.setName("消费者-》");
        p.start();
        c.start();

    }
}
class  Box {
    private int content;
    private boolean has;

    public synchronized void setContent(int contet) {
        if (has) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.content = content;
        has = true;
        notifyAll();
    }

    public synchronized int getContet() {
        if (has == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
         has=false;
        notifyAll();
        return content;

    }

}
class  Custermer extends  Thread{
    private  Box box;
  public   Custermer(Box box){this.box=box;}

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName()+",取"+box.getContet()+"个");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class  Product extends Thread{

    private  Box box;
    private  int i=1;
    public  Product(Box box){this.box=box;
    }

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName()+",方"+i+"个");
            box.setContent(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}